/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sf.mysql.tool;

import com.mysql.jdbc.StringUtils;
import com.sf.mysql.tool.excel.WriteExcel;
import com.sf.mysql.tool.utils.DBUtils;
import com.sf.mysql.tool.vo.TableVo;

import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;

/**
 *
 * @author Administrator
 */
public class EditorUI extends javax.swing.JFrame {

    /**
     * Creates new form EditorUI
     */
    public EditorUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        hostLabel = new javax.swing.JLabel();
        hostText = new javax.swing.JTextField();
        portLable = new javax.swing.JLabel();
        portText = new javax.swing.JTextField();
        userLabel = new javax.swing.JLabel();
        userText = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        connTestBtn = new javax.swing.JButton();
        pathLabel = new javax.swing.JLabel();
        pathText = new javax.swing.JTextField();
        pathSelectBtn = new javax.swing.JButton();
        buildBtn = new javax.swing.JButton();
        fileTypeBox = new javax.swing.JComboBox<>();
        fileTypeLabel = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        logTextArea = new javax.swing.JTextArea();
        clearBtn = new javax.swing.JButton();
        passwordText = new javax.swing.JPasswordField();
        dbLabel = new javax.swing.JLabel();
        dbText = new javax.swing.JTextField();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);

        jMenu1.setText("jMenu1");

        jMenuItem1.setText("jMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        hostLabel.setText("IP地址:");

        hostText.setText("127.0.0.1");
        hostText.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hostTextActionPerformed(evt);
            }
        });

        portLable.setText("端口号:");

        portText.setText("3306");
        portText.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                portTextActionPerformed(evt);
            }
        });

        userLabel.setText("用户名:");

        userText.setText("root");
        userText.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userTextActionPerformed(evt);
            }
        });

        passwordLabel.setText("密码:");

        connTestBtn.setText("连接测试");
        connTestBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                connTestBtnMouseClicked(evt);
            }
        });
        connTestBtn.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connTestBtnActionPerformed(evt);
            }
        });

        pathLabel.setText("保存路径:");

        pathText.setText("");
        pathText.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pathTextActionPerformed(evt);
            }
        });

        pathSelectBtn.setText("选择");
        pathSelectBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pathSelectBtnMouseClicked(evt);
            }
        });
        pathSelectBtn.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pathSelectBtnActionPerformed(evt);
            }
        });

        buildBtn.setText("点击生成");
        buildBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buildBtnMouseClicked(evt);
            }
        });
        buildBtn.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buildBtnActionPerformed(evt);
            }
        });

        fileTypeBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Excel" }));
        fileTypeBox.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileTypeBoxActionPerformed(evt);
            }
        });

        fileTypeLabel.setText("文件类型:");

        logTextArea.setColumns(20);
        logTextArea.setRows(5);
        logTextArea.setText("1.填好基本信息,点击连接测试,测试通过后再往下\n2.选择文件保存的路径\n3.建议选择excel,点击生成文档\n4.已生成过的文档,建议清除或备份后再生成,避免重复");
        jScrollPane3.setViewportView(logTextArea);

        clearBtn.setText("清除");
        clearBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clearBtnMouseClicked(evt);
            }
        });

        passwordText.setText("");
        passwordText.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passwordTextActionPerformed(evt);
            }
        });

        dbLabel.setText("数据库名:");

        dbText.setText("dataBase");
        dbText.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbTextActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(userLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(userText, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(hostLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(hostText, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(portLable)
                            .addComponent(passwordLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
                            .addComponent(portText, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
                        .addGap(75, 75, 75))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane3)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(64, 64, 64)
                        .addComponent(connTestBtn)
                        .addGap(18, 18, 18)
                        .addComponent(buildBtn)
                        .addGap(85, 151, Short.MAX_VALUE)
                        .addComponent(clearBtn))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dbLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dbText, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(fileTypeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(fileTypeBox, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(151, 250, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(pathLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pathText)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pathSelectBtn))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hostLabel)
                    .addComponent(hostText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portLable)
                    .addComponent(portText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userLabel)
                    .addComponent(userText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbLabel)
                    .addComponent(dbText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathLabel)
                    .addComponent(pathText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pathSelectBtn))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fileTypeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fileTypeLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connTestBtn)
                    .addComponent(buildBtn)
                    .addComponent(clearBtn))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void hostTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hostTextActionPerformed
    }//GEN-LAST:event_hostTextActionPerformed

    private void userTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userTextActionPerformed
    }//GEN-LAST:event_userTextActionPerformed

    private void connTestBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connTestBtnActionPerformed
          
    }//GEN-LAST:event_connTestBtnActionPerformed

    private void pathTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pathTextActionPerformed
    }//GEN-LAST:event_pathTextActionPerformed

    private void fileTypeBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileTypeBoxActionPerformed
    }//GEN-LAST:event_fileTypeBoxActionPerformed

    private void connTestBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_connTestBtnMouseClicked
        String host = hostText.getText().trim();
        String port = portText.getText().trim();
        String user = userText.getText().trim();
        String password = passwordText.getText();
        String db = dbText.getText().trim();
        Parameters parameters = new Parameters();
        parameters.setDatabase(db);
        parameters.setHost(host);
        parameters.setPort(port);
        parameters.setUser(user);
        parameters.setPassword(password);
        DBUtils dbUtils = new DBUtils(parameters);

        try {
            if(dbUtils.connectable()){
                logTextArea.append("\n 连接成功!" );
                JOptionPane.showMessageDialog(null,"测试连接成功", " 测试连接结果", JOptionPane.INFORMATION_MESSAGE);
            } else {
                logTextArea.append("\n 连接失败!" );
                JOptionPane.showMessageDialog(null,"连接失败！", " 测试连接结果", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException e) {
            logTextArea.append("\n 连接失败:"  + e.getMessage());
            JOptionPane.showMessageDialog(null, e.getMessage(), " 测试连接结果", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_connTestBtnMouseClicked

    private void buildBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buildBtnMouseClicked
        String path = pathText.getText().trim();
        String host = hostText.getText().trim();
        String port = portText.getText().trim();
        String user = userText.getText().trim();
        String password = passwordText.getText();
        String db = dbText.getText().trim();
        if(StringUtils.isNullOrEmpty(path) || StringUtils.isNullOrEmpty(host) ||StringUtils.isNullOrEmpty(port)
                ||StringUtils.isNullOrEmpty(user) ||StringUtils.isNullOrEmpty(password) ||StringUtils.isNullOrEmpty(db)){
            logTextArea.append("\n 信息内容请填写完整！");
            JOptionPane.showMessageDialog(null,"信息内容请填写完整！", " 信息结果", JOptionPane.ERROR_MESSAGE);
            return;
        }
        Parameters parameters = new Parameters();
        parameters.setDatabase(db);
        parameters.setHost(host);
        parameters.setPort(port);
        parameters.setUser(user);
        parameters.setPassword(password);
        logTextArea.append("\n …………正在生成过程中");
        try {
            createByExcel(parameters,getExcelFileName(path,db));
        } catch (Exception e) {
            logTextArea.append("\n 生成失败！" + e.getMessage());
            JOptionPane.showMessageDialog(null, "生成失败! " + e.getMessage(), " 生成结果", JOptionPane.ERROR_MESSAGE);
            return;
        }
        JOptionPane.showMessageDialog(null, "恭喜,文件生成成功 ", " 生成结果", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_buildBtnMouseClicked

    private static void createByExcel(Parameters parameters,String fileName)throws Exception{
        DBUtils dbUtils = new DBUtils(parameters);
        List<TableVo> tableVoList = dbUtils.getTableList();
        for(TableVo table : tableVoList) {
            List<List<String>> headList = WriteExcel.getHeadList(table.getTableName(),table.getTableComment());
            List<List<String>> bodyList = WriteExcel.getBodyList(table);
            headList.addAll(bodyList);
            WriteExcel.inputExcelHead(headList,table.getTableName(),fileName);
        }
    }

    private static String getExcelFileName(String dirPath,String database) {
        return dirPath + "\\" + database + ".xlsx";
    }

    private static void createByWord(Parameters parameters,String fileName) throws Exception{
        parameters.setPath(fileName);
        DBUtils dbUtils = new DBUtils(parameters);
        Map<String, HashMap<String, LinkedHashMap<String, String>>> data = dbUtils.getDatabaseInfo();
        Word2007.productWordForm(data, parameters);
    }

    private void portTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_portTextActionPerformed

    }//GEN-LAST:event_portTextActionPerformed

    private void clearBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearBtnMouseClicked
        logTextArea.setText("");
    }//GEN-LAST:event_clearBtnMouseClicked

    private void passwordTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_passwordTextActionPerformed

    private void pathSelectBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pathSelectBtnActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_pathSelectBtnActionPerformed

    private void pathSelectBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pathSelectBtnMouseClicked
         JFileChooser chooser = new JFileChooser();
         chooser.setMultiSelectionEnabled(false);
         chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
         chooser.setDialogTitle("请选择存放路径");
         int result = chooser.showOpenDialog(this);
         if(result == JFileChooser.APPROVE_OPTION){
             File file  = chooser.getSelectedFile();
             String path = file.getAbsolutePath().trim();
//             if(StringUtils.isNullOrEmpty(path)){
//
//             }else {
//                 path += "\\result.xlsx";
//             }
             pathText.setText(path);
         }
    }//GEN-LAST:event_pathSelectBtnMouseClicked

    private void buildBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buildBtnActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_buildBtnActionPerformed

    private void dbTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dbTextActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EditorUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buildBtn;
    private javax.swing.JButton clearBtn;
    private javax.swing.JButton connTestBtn;
    private javax.swing.JLabel dbLabel;
    private javax.swing.JTextField dbText;
    private javax.swing.JComboBox<String> fileTypeBox;
    private javax.swing.JLabel fileTypeLabel;
    private javax.swing.JLabel hostLabel;
    private javax.swing.JTextField hostText;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea logTextArea;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JPasswordField passwordText;
    private javax.swing.JLabel pathLabel;
    private javax.swing.JButton pathSelectBtn;
    private javax.swing.JTextField pathText;
    private javax.swing.JLabel portLable;
    private javax.swing.JTextField portText;
    private javax.swing.JLabel userLabel;
    private javax.swing.JTextField userText;
    // End of variables declaration//GEN-END:variables
}
